package com.keiou.drink.ui.activity.base;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import com.keiou.drink.AppContext;
import com.keiou.drink.R;
import com.keiou.drink.api.HttpCode;
import com.keiou.drink.ui.activity.RestActivity;
import com.keiou.drink.util.AppManager;
import com.keiou.drink.util.UIUtil;
import com.keiou.drink.widget.LoadingDialog;

import butterknife.ButterKnife;

/**
 * 作者 ：Bob on 2017/8/1.
 * 邮箱 ：motherlovefather@126.com
 */

public abstract class BaseActivity extends AppCompatActivity {

    private LoadingDialog _waitDialog;

    private ImageView iv_back;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppManager.getInstance().addActivity(this);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        int layoutResID = getLayoutId();
        if (0 != layoutResID) {
            setContentView(layoutResID);
        }
        ButterKnife.bind(this);
        initBack();
        initData();
        initViews(savedInstanceState);
        loadData();
    }

    private void initBack(){
        iv_back = (ImageView) findViewById(R.id.iv_back);
        if(null != iv_back){
            iv_back.setOnClickListener(view -> finish());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        UIUtil.hideSoftKeyboard(this);
        AppManager.getInstance().removeActivity(this);
        AppContext.getRefWatcher().watch(this);
    }


    public void showLoadingDialog() {
        showLoadingDialog(null);
    }

    public void showLoadingDialog(String tip) {
        if (isFinishing()) return;
        if (null == _waitDialog) {
            _waitDialog = new LoadingDialog(this);
        }
        _waitDialog.setCanceledOnTouchOutside(false);
        _waitDialog.show();
        _waitDialog.setTip(tip);
    }

    public void hideWaitDialog() {
        if (isFinishing()) return;
        if (null != _waitDialog) {
            _waitDialog.dismiss();
            _waitDialog = null;
        }
    }


    protected abstract int getLayoutId();

    protected abstract void initViews(Bundle savedInstanceState);

    protected abstract void initData();

    protected abstract void loadData();

    protected void onInterceptCode(int code){


        if(HttpCode.SYS_RESET_CODE == code){
            Intent intent = new Intent(this, RestActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }

    }

}
